package org.megha.blog.example.concurrency;

import java.io.IOException;

/**
 * An example of how to write an interruptible thread that breaks loop immediately.
 * 
 * @author megha birmiwal
 */
public class InterruptibleThread extends Thread {

	private boolean continueRunning = true;

	@Override
	public void run() {
		System.out.println("in thread");
		while (continueRunning) {
			System.out.println("tick..");
			try {
				Thread.sleep(15000);
			} catch (InterruptedException e) {
				System.out.println("Thread was interrupted");
				e.printStackTrace();
			}
		}
	}

	public void requestTerminate() {
		continueRunning = false;
		interrupt();
	}

	public static void main(String args[]) {
		InterruptibleThread thread1 = new InterruptibleThread();
		System.out.println("starting thread");
		thread1.start();

		System.out.println("waiting for user input; press the enter key");
		try {
			System.in.read();
		} catch (IOException e) {
			e.printStackTrace();
		}
		thread1.requestTerminate();

		System.out.println("waiting for print-thread to finish");
		try {
			thread1.join();
		} catch (InterruptedException e) {
			System.out.println("Main thread was interrupted");
			e.printStackTrace();
		}
		System.out.println("all done");
	}
}
